package com.atguigu.gulimall.seckill.interceptor;

import com.atguigu.common.constant.AuthConstant;
import com.atguigu.common.to.MemberVo;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //TODO 通过openFeign发的请求没带cookie，先放行
        AntPathMatcher antPathMatcher = new AntPathMatcher();

        if (antPathMatcher.match("/kill",request.getRequestURI())){
            HttpSession session = request.getSession();
            Object attribute = session.getAttribute(AuthConstant.LOGIN_USER);
            if(attribute != null){
                loginUser.set((MemberVo) attribute);
                return true;
            }else{
                session.setAttribute("errorMessage","请先登录");
                response.sendRedirect("http://auth.gulimall.com/login.html");
                return false;
            }
        }else {
            return true;
        }
    }
}
